﻿using PagedList;
using System;
using System.Collections.Generic;
using System.Linq;

namespace VehicleOOBWeb.Models
{
    public class ManufacturerService
    {
        public static IEnumerable<Manufacturer> GetAllManufacturers()
        {
            using (DataVehicleDataContext db = new DataVehicleDataContext())
            {
                
                var manufacturers = from p in db.Manufacturers
                                    select p;
                return manufacturers.ToList(); 
            }
        }

        public static Manufacturer GetManufacturerByCode(int manufacturerCode)
        {
            using (DataVehicleDataContext db = new DataVehicleDataContext())
            {

                Manufacturer manufacturer = db.Manufacturers.Where(p => p.manufacturer_code == manufacturerCode).SingleOrDefault();
                return manufacturer;
            }
        }

        public static bool AddManufacturer(Manufacturer entity)
        {
            using (DataVehicleDataContext db = new DataVehicleDataContext())
            {
                db.Manufacturers.InsertOnSubmit(entity);
                db.SubmitChanges();
                return true;
            }
        }

        public static bool UpdateManufacturer(Manufacturer entity)
        {
            using (DataVehicleDataContext db = new DataVehicleDataContext())
            {
                Manufacturer manufacturer = 
                    db.Manufacturers.FirstOrDefault(m => m.manufacturer_code == entity.manufacturer_code);
                if (manufacturer != null)
                {
                    manufacturer.manufacturer_name = entity.manufacturer_name;
                    db.SubmitChanges();
                }
                return true;
            }
        }

        public static bool DeleteManufacturer(int manufacturercode)
        {
            using (DataVehicleDataContext db = new DataVehicleDataContext())
            {
                Manufacturer manufacturer = 
                    db.Manufacturers.FirstOrDefault(m => m.manufacturer_code == manufacturercode);
                if (manufacturer != null)
                {
                    if (manufacturer.Vehicles != null && manufacturer.Vehicles.Count > 0)
                    {
                        db.Vehicles.DeleteAllOnSubmit(manufacturer.Vehicles);
                    }
                    db.Manufacturers.DeleteOnSubmit(manufacturer);
                    db.SubmitChanges();
                }
                return true;
            }
        }

        public static IPagedList<Manufacturer> GetListManufacturersPagging(int pageNumber)
        {
            using (DataVehicleDataContext db = new DataVehicleDataContext())
            {
                return db.Manufacturers.ToPagedList(pageNumber, Config.PageSize);
            }
        }
    }
}

